package com.wenhao.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 独占锁（写锁）
 * 共享锁（读锁）
 *
 * 读和读 可以共存
 * 读和写 不能共存
 * 写和写 不能共存
 *
 * @author Wenhao Tong
 * @create 2021-08-20 12:57
 */
public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0;i < 10;i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.put(String.valueOf(temp),"Hello");
            },String.valueOf(i)).start();
        }

        for (int i = 0;i < 10;i++) {
            final int temp = i;
            new Thread(() -> {
                myCache.get();
            },String.valueOf(i)).start();
        }
    }

}

class MyCache {
    private volatile Map<String,Object> map = new HashMap<>();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName() + "写入完成");
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void get() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取完成");
        } finally {
            lock.readLock().unlock();
        }
    }
}
